﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;

using FileSecurityManager.BizLogic;

using Microsoft.Windows.Controls;

namespace FileSecurityManager.UI.UserControls
{
    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;

    /// <summary>
    /// Interaction logic for UserFilesCtl.xaml
    /// </summary>
    public partial class UserFilesCtl
    {
        private readonly string folder = string.Empty;

        public UserFilesCtl()
        {
            InitializeComponent();

            if (LoginLogic.CurrentUser.UserOptions != null)
            {
                folder = LoginLogic.CurrentUser.UserOptions.WorkingDir;
            }
        }

        /// <summary>
        /// Handles the Loaded event of the userControl control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void userControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (Directory.Exists(folder))
            {
                //fileView.AutoGeneratingColumn += fileView_AutoGeneratingColumn;

                var root = new ObservableCollection<DirectoryRecord>
                    {
                        new DirectoryRecord
                            {
                                Info = new DirectoryInfo(folder) 
                    }
                };

                directoryView.ItemsSource = root;
            }
        }

        /// <summary>
        /// Handles the AutoGeneratingColumn event of the fileView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Microsoft.Windows.Controls.DataGridAutoGeneratingColumnEventArgs"/> instance containing the event data.</param>
        private void fileView_AutoGeneratingColumn(
            object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            var requiredProperties = new List<string>
            {
                "Name", "Length", "LastWriteTime"
            };

            if (!requiredProperties.Contains(e.PropertyName))
            {
                e.Cancel = true;
            }
            else
            {
                e.Column.Header = e.Column.Header.ToString().MixedCaseToSpace();
            }
        }

        #region tree view context menu

        /// <summary>
        /// Searches the tree view.
        /// </summary>
        /// <typeparam name="T">Tree view type</typeparam>
        /// <param name="source">The source.</param>
        /// <returns>DependencyObject instance</returns>
        private static DependencyObject SearchTreeView<T>(DependencyObject source)
        {
            while (source != null && source.GetType() != typeof(T))
            {
                source = VisualTreeHelper.GetParent(source);
            }
            return source;
        }

        /// <summary>
        /// Handles the PreviewMouseRightButtonDown event of the directoryView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param>
        private void directoryView_PreviewMouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            TreeViewItem treeViewItem = (TreeViewItem)SearchTreeView<TreeViewItem>((DependencyObject)e.OriginalSource);
            if (treeViewItem != null)
            {
                treeViewItem.IsSelected = true;
                e.Handled = true;
            }
        }

        /// <summary>
        /// Handles the Click event of the miAddFile control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void miAddFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (directoryView.SelectedValue is DirectoryRecord)
                {
                    var directoryRecord = directoryView.SelectedValue as DirectoryRecord;
                    string fullPath = directoryRecord.Info.FullName;

                    var openFileDialog = new Microsoft.Win32.OpenFileDialog
                    {
                        Multiselect = false,
                        Filter = "All Image Files | *.*"
                    };

                    if ((bool)openFileDialog.ShowDialog())
                    {
                        if (File.Exists(openFileDialog.FileName))
                        {
                            string newFilePath = Path.Combine(fullPath, Path.GetFileName(openFileDialog.FileName));
                            File.Copy(openFileDialog.FileName, newFilePath);
                        }
                    }

                    MessageBox.Show("File is added", "Success");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Could not add file", "Error");
            }
        }
        #endregion

        private void TextBlock_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue is FileInfo)
            {
                bool isEncrypted = (((FileInfo)e.NewValue).Attributes & FileAttributes.Temporary) == FileAttributes.Temporary;

                ((TextBlock)sender).Text = isEncrypted ? "Decrypt" : "Encrypt";
            }
        }

        private void TextBlock_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            try
            {
                TextBlock tb = sender as TextBlock;
                if (tb != null)
                {
                    FileInfo fileInfo = tb.Tag as FileInfo;
                    
                    bool isEncrypted = (fileInfo.Attributes & FileAttributes.Temporary) == FileAttributes.Temporary;
                    if (isEncrypted)
                    {
                        SecureFileLogic.Decrypt(fileInfo.FullName, fileInfo.FullName + "1", LoginLogic.CurrentUser.UserName);
                    }
                    else
                    {
                        SecureFileLogic.Encrypt(fileInfo.FullName, fileInfo.FullName + "1", LoginLogic.CurrentUser.UserName);
                    }

                    MessageBox.Show("Success!!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error!!!");
            }
        }
    }

    internal class DirectoryRecord
    {
        public DirectoryInfo Info { get; set; }

        public IEnumerable<FileInfo> Files
        {
            get
            {
                return Info.GetFiles();
            }
        }

        public IEnumerable<DirectoryRecord> Directories
        {
            get
            {
                return from di in Info.GetDirectories("*", SearchOption.AllDirectories)
                       select new DirectoryRecord { Info = di };
            }
        }
    }

    internal static class Extensions
    {
        /// <summary>
        /// Mixeds the case to space.
        /// </summary>
        /// <param name="s">The s.</param>
        /// <returns></returns>
        public static string MixedCaseToSpace(this string s)
        {
            var sb = new StringBuilder();
            sb.Append(s[0]);
            for (int i = 1; i < s.Length; i++)
            {
                if (char.IsUpper(s[i]))
                {
                    sb.Append(' ');
                }
                sb.Append(s[i]);
            }
            return sb.ToString();
        }
    }
    
}
